<template>
  <div class="node-wrap">
    <div class="node-wrap-box" @click="show">
      <div class="title" style="background: #ff7d00">
        <el-icon class="icon"><el-icon-user-filled /></el-icon>
        <span>{{ nodeConfig.node_name }}</span>
        <icon-close class="close" @click.stop="delNode()" />
      </div>
      <div class="content">
        <span v-if="toText(nodeConfig)">
          <span v-if="nodeConfig.approve_type === 1">
            审核人员：
            <a-tag
              class="tagss"
              v-for="item in toText(nodeConfig)"
              :key="item"
              color="#165dff"
              @close="closeTag(item)"
            >
              <template #icon> <icon-user style="color: white" /> </template
              >{{ item }}</a-tag
            >
          </span>
          <span v-if="nodeConfig.approve_type === 2">
            审核角色：
            <a-tag
              class="tagss"
              v-for="item in toText(nodeConfig)"
              :key="item"
              color="#ff5722"
              @close="closeTag(item)"
            >
              <template #icon>
                <icon-idcard style="color: white" :size="16" /> </template
              >{{ item }}</a-tag
            >
          </span>
          <span v-if="nodeConfig.approve_type === 3">
            审核部门：
            <a-tag
              class="tagss"
              v-for="item in toText(nodeConfig)"
              :key="item"
              color="#0fc6c2"
              @close="closeTag(item)"
            >
              <template #icon>
                <icon-stamp style="color: white" :size="16" /> </template
              >{{ item }}</a-tag
            >
          </span>
          <span v-if="nodeConfig.approve_type === 4">
            <a-tag style="margin-right: 5px" color="#ff5722">
              发起人自选
            </a-tag>
          </span>
        </span>
        <span v-else class="placeholder">请选择</span>
      </div>
    </div>
    <a-drawer title="审批人设置" :visible="drawer" :width="500" :footer="false">
      <template #header>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          "
        >
          <div class="node-wrap-drawer__title">
            <label @click="editTitle" v-if="!isEditTitle"
              >{{ form.node_name }}
              <icon-edit />
            </label>
            <a-input
              allow-clear
              v-if="isEditTitle"
              ref="nodeTitle"
              v-model="form.node_name"
              :style="{ width: '320px' }"
              @blur="saveTitle"
              @press-enter="saveTitle"
            />
          </div>
          <div
            style="cursor: pointer"
            @click="
              () => {
                drawer = false;
              }
            "
          >
            <icon-close size="15"
          /></div>
        </div>
      </template>
      <a-form ref="formRef" :model="form">
        <a-form-item label="节点类型">
          <a-tag field="node_type" color="#FFF3E8" style="margin-right: 20px">
            <span style="color: #f7783c">审核节点</span>
          </a-tag>
        </a-form-item>
        <a-form-item field="approve_type" label="审批人类型">
          <a-select
            v-model="form.approve_type"
            placeholder="请选择"
            @change="changeSelect"
          >
            <a-option
              v-for="item in approveOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="approve_sign_type" label="审批方式">
          <a-radio-group :default-value="1" v-model="form.approve_sign_type">
            <template
              v-for="(item, index) in shenpiType"
              :key="item.label + index"
            >
              <a-radio :value="item.value">
                <template #radio="{ checked }">
                  <a-space
                    align="start"
                    class="custom-radio-card"
                    :class="{ 'custom-radio-card-checked': checked }"
                  >
                    <div class="custom-radio-card-mask">
                      <div class="custom-radio-card-mask-dot" />
                    </div>
                    <div>
                      <div class="custom-radio-card-title">
                        {{ item.label }}
                      </div>
                      <a-typography-text type="secondary">
                        {{ item.des }}
                      </a-typography-text>
                    </div>
                  </a-space>
                </template>
              </a-radio>
            </template>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="node_assignee_list" label="审批列表">
          <!-- 指定人员-->
          <div v-if="form.approve_type === undefined" style="color: green"
            >请选择审批人类型</div
          >
          <div v-if="form.approve_type === 1">
            <a-row>
              <a-button
                @click="
                  () => {
                    visible = true;
                  }
                "
              >
                <template #icon>
                  <icon-user />
                </template>
                <template #default>选择人员</template>
              </a-button>
            </a-row>
            <a-space style="margin-top: 10px; display: flex; flex-wrap: wrap">
              <a-tag
                class="tagss"
                v-for="item in showSelectUser"
                :key="item"
                color="#165dff"
              >
                <template #icon>
                  <icon-user style="color: white" />
                </template>

                {{ item.user_name }}</a-tag
              >
            </a-space>
          </div>
          <!--          指定角色-->
          <div v-if="form.approve_type === 2" style="width: 100%">
            <a-select
              multiple
              placeholder="请选择"
              v-model="form.node_assignee_list"
            >
              <a-option
                v-for="(item, index) in allROle"
                :key="item.role_id + index"
                :value="item.role_id"
              >
                {{ item.role_name }}
              </a-option>
            </a-select>
          </div>
          <!--          选择部门-->
          <div v-if="form.approve_type === 3" style="width: 100%">
            <a-tree-select
              :data="
                transformDeptTreeSelect(store.allDepts, 'dept_id', 'dept_id')
              "
              v-model="form.node_assignee_list"
              placeholder="请选择"
              :allow-search="true"
              :allow-clear="true"
              style="width: 100%"
              :multiple="true"
            ></a-tree-select>
          </div>
          <div v-if="form.approve_type === 4">
            <a-space> <a-tag color="red">发起人自选</a-tag> </a-space></div
          >
        </a-form-item>
        <a-form-item style="margin-top: 30px">
          <a-space>
            <a-button html-type="submit" type="primary" @click="save"
              >保存</a-button
            >
            <a-button @click="$refs.formRef.resetFields()">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-modal
      title="选择人员"
      :visible="visible"
      width="600px"
      height="1000px"
      @ok="handleSubmit"
      title-align="start"
      @cancel="
        () => {
          visible = false;
        }
      "
    >
      <a-row gutter="5">
        <a-col span="10">
          <a-card title="部门列表">
            <div style="display: flex; align-items: center; margin-top: 10px">
              <a-spin
                style="
                  margin: 0 auto;
                  margin-top: 20px;
                  min-height: 50px;
                  justify-content: center;
                "
                v-if="loading"
                dot
              />
              <a-tree
                v-else
                default-expand-all
                blockNode
                :data="treeData"
                v-model:checked-keys="selectKeys"
                @select="handleNodeSelect"
                :key="treeKey"
                :check-strictly="true"
              />
            </div>
            <template #extra>
              <a-tooltip content="重置">
                <div @click="resetTable">
                  <icon-loop size="20" />
                </div>
              </a-tooltip>
            </template>
          </a-card>
        </a-col>
        <a-col span="14">
          <a-card title="人员列表" v-loading="isloading">
            <a-checkbox-group
              direction="vertical"
              v-model="selectUser"
              v-if="allUser.length > 0"
            >
              <a-checkbox
                v-for="(item, index) in allUser"
                :value="item.user_id"
                >{{ item.user_name }}</a-checkbox
              >
            </a-checkbox-group>
            <a-empty v-else />
          </a-card>
        </a-col>
      </a-row>
    </a-modal>
    <add-node v-model="nodeConfig.child_node"></add-node>
  </div>
</template>

<script>
  import addNode from './addNode.vue';
  import { Select, Option } from '@arco-design/web-vue';
  import { useUserStore } from '@/store/index';
  import { transformDeptTree, transformDeptTreeSelect } from '@/utils/utils';
  import { Message } from '@arco-design/web-vue';
  import { getAllRole, getDept, getUserList } from '@/api/syssetting';
  export default {
    inject: ['select'],
    props: {
      modelValue: { type: Object, default: () => {} },
    },
    components: {
      addNode,
      aSelect: Select,
      aOption: Option,
    },
    data() {
      return {
        store: useUserStore(),
        nodeConfig: {},
        drawer: false,
        isEditTitle: false,
        form: {},
        showSelectUser: [],
        allUser: [],
        isloading: true,
        selectUser: [],
        loading: true,
        currentKeys: '',
        selectKeys: [],
        treeKey: 0,
        currentCompany: '',
        visible: false,
        transformDeptTreeSelect: transformDeptTreeSelect,
        store: useUserStore(),
        shenpiType: [
          {
            label: '顺签',
            des: '按顺序依次审批',
            value: 1,
          },
          {
            label: '会签',
            des: '可同时审批，每个人必须审批通过',
            value: 2,
          },
          {
            label: '或签',
            des: '有一人审批通过即可',
            value: 3,
          },
        ],
        approveOptions: [
          { value: 1, label: '指定人员' },
          { value: 2, label: '指定角色' },
          { value: 3, label: '指定部门' },
        ],
        treeData: [],
        allROle: '',
      };
    },
    watch: {
      modelValue() {
        this.nodeConfig = this.modelValue;
      },
    },
    mounted() {
      this.nodeConfig = this.modelValue;
      getAllRole().then((res) => {
        this.allROle = res.data;
      });
      this.getDeptList();
      this.getUserAll();
    },
    methods: {
      closeTag(e) {
        if (this.form.approve_type == 1) {
          console.log('人员');
        } else if (this.form.approve_type == 2) {
          console.log('校色', e, this.form.node_assignee_list);
        } else if (this.form.approve_type == 3) {
          console.log('部门');
        }
      },
      resetTable() {
        this.selectKeys = []; // 清空选中的 keys
        this.currentKeys = '';
        this.treeKey = this.treeKey + 1;
        this.getUserAll();
      },
      handleNodeSelect(event, data) {
        this.currentKeys = data.node.id; // 存储第一个选中节点的key
        this.getUserAll();
      },
      changeSelect() {
        this.nodeConfig.node_assignee_list = [];
        this.form.node_assignee_list = [];
        this.showSelectUser = '';
      },
      async getUserAll() {
        this.isloading = true;
        const res = await getUserList({
          page_size: 1000,
          user_dept_id: this.currentKeys,
        });
        this.allUser = res.data.list;
        // 创建 id 映射表（优化查找效率）
        this.userMap = new Map(
          this.allUser.map((user) => [user.user_id, user])
        );
        this.isloading = false;
      },
      getDeptList() {
        getDept({
          page_on: 1,
          page_size: 1000,
        })
          .then((res) => {
            this.loading = true;
            this.treeData = transformDeptTree(res.data.list, '0-0', 'dept_id');
            this.currentKeys = this.treeData[0]?.id;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      show() {
        this.form = {};
        this.form = JSON.parse(JSON.stringify(this.nodeConfig));
        this.drawer = true;

        // 匹配人员
        const selectedUsers = this.form.node_assignee_list.map((userId) => {
          const user = this.store.allUser.find((u) => u.user_id === userId);
          return { user_id: userId, user_name: user?.user_name || '未知用户' }; // 确保字段存在
        });
        this.showSelectUser = selectedUsers;
      },
      editTitle() {
        this.isEditTitle = true;
        this.$nextTick(() => {
          this.$refs.nodeTitle.focus();
        });
      },
      saveTitle() {
        this.isEditTitle = false;
      },
      handleSubmit() {
        if (this.selectUser.length <= 0) {
          Message.error('请至少选择一个用户');
          return false;
        }
        const selectedUsers = this.selectUser.map((userId) => {
          const user = this.allUser.find((u) => u.user_id === userId);
          return { user_id: userId, user_name: user?.user_name || '' }; // 确保字段存在
        });

        this.showSelectUser = selectedUsers;
        // 将整合后的数组赋值给表单的 node_assignee_list（用于显示）
        this.form.node_assignee_list = this.selectUser;
        // 关闭模态框
        this.visible = false;
      },
      save() {
        this.$emit('update:modelValue', this.form);
        this.drawer = false;
      },
      delNode() {
        this.$emit('update:modelValue', this.nodeConfig.child_node);
      },
      selectHandle(type, data) {
        this.select(type, data);
      },
      toText(nodeConfig) {
        if (nodeConfig.approve_type === 1) {
          if (nodeConfig.node_assignee_list.length <= 0) {
            return false;
          }
          return this.store.allUser
            .filter((user) =>
              nodeConfig.node_assignee_list.includes(user.user_id)
            )
            .map((user) => user.user_name);
        } else if (nodeConfig.approve_type == 2) {
          if (nodeConfig.node_assignee_list.length <= 0) {
            return false;
          }
          return this.store.allRole
            .filter((role) =>
              nodeConfig.node_assignee_list.includes(role.role_id)
            )
            .map((role) => role.role_name);
        } else if (nodeConfig.approve_type === 3) {
          if (nodeConfig.node_assignee_list.length <= 0) {
            return false;
          }
          const getAllDepts = (depts) => {
            return depts.flatMap((dept) => [
              dept,
              ...(dept.children && dept.children.length > 0
                ? getAllDepts(dept.children)
                : []),
            ]);
          };
          const allLevelDepts = getAllDepts(this.store.allDept);
          return allLevelDepts
            .filter((dept) =>
              nodeConfig.node_assignee_list.includes(dept.dept_id)
            )
            .map((dept) => dept.dept_name);
        } else if (nodeConfig.approve_type === 4) {
          return '发起人自选';
        }
      },
    },
  };
</script>

<style lang="less" scoped>
  .custom-radio-card {
    margin-bottom: 10px;
    padding: 5px 10px;
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    width: 280px;
    box-sizing: border-box;
  }

  .custom-radio-card-mask {
    height: 14px;
    width: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
  }

  .custom-radio-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 100%;
  }

  .custom-radio-card-title {
    color: var(--color-text-1);
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .custom-radio-card:hover,
  .custom-radio-card-checked,
  .custom-radio-card:hover .custom-radio-card-mask,
  .custom-radio-card-checked .custom-radio-card-mask {
    border-color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked {
    background-color: var(--color-primary-light-1);
  }

  .custom-radio-card:hover .custom-radio-card-title,
  .custom-radio-card-checked .custom-radio-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked .custom-radio-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }
  .tagss {
    margin-right: 5px;
    margin-bottom: 5px;
  }
</style>
